from feishu.config import settings
import requests
import arrow
import datetime
from requests.adapters import HTTPAdapter
import json
from loguru import logger

from feishu.utils import gen_sign
#带校验的发送
def send_sign(data):
    url=settings.feishu_url
    headers = {'Content-Type': 'application/json; charset=utf-8'}
    if settings.feishu_url == "" or settings.secret == "":
        logger.error("没有设置secret和url")
        return
    # 获取时间戳和签名
    timestamp = int(datetime.datetime.now().timestamp())
    sign = gen_sign.gen_sign(timestamp, settings.secret)
    alerts = data['alerts']   
    for output in alerts:
        try:
            summary=output['annotations']['summary'] 
        except KeyError: 
            summary='null'  
        try:
            description=output['annotations']['description'] 
        except KeyError: 
            description='null'    
        title = f"平台监控告警通知: {output['labels']['alertname']}"
        warning_name = output['labels']['alertname']
        warning_status = output['status']  
        warning_isfiring = output['status']
        warning_level = output['labels']['severity']
        warning_instance = output['labels']['instance'] 
        warning_start_time = arrow.get(output['startsAt']).to('Asia/Shanghai').format('YYYY-MM-DD HH:mm:ss')
        warning_end_time = arrow.get(output['endsAt']).to('Asia/Shanghai').format('YYYY-MM-DD HH:mm:ss')
        now_time = str(datetime.datetime.now().replace(microsecond=0))
        now_time_struct = str(datetime.datetime.strptime(now_time, "%Y-%m-%d %H:%M:%S"))

        if settings.feishu_alert_type == "post":
            send_data={
                "timestamp": timestamp,
                "sign": sign,
                "msg_type": "post",
                "content":{
                    "post":{
                        "zh_cn":{
                            "title": title,
                            "content":[
                                [
                                    {"tag": "text", "text": f"告警实例: {warning_instance} \n"},
                                    {"tag": "text", "text": f"当前时间: {now_time_struct} \n"},
                                    {"tag": "text", "text": f"告警等级: {warning_level} \n"},                           
                                    {"tag": "text", "text": f"当前状态: {warning_status} \n"},
                                    {"tag": "text", "text": f"故障时间: {warning_start_time} \n"},
                                    {"tag": "text", "text": f"恢复时间: {warning_end_time} \n"},  
                                    {"tag": "text", "text": f"告警主题: {summary} \n"},
                                    {"tag": "text", "text": f"告警详情: {description} \n"},
                                ]
                            ]
                
                        }
                    }
                }
            }
        elif settings.feishu_alert_type == "interactive":
            title = f"%s告警通知" %warning_level
            send_data = {
                "timestamp": timestamp,
                "sign": sign,
                "msg_type": "interactive",
                "card": {
                    "config": {"update_multi": True },
                    "i18n_elements": {
                        "zh_cn": [
                            {"tag": "hr"},
                            {
                            "tag": "markdown",
                            "content": f"**告警名称:**{warning_name}\n**故障节点: **{warning_instance}\n**告警状态:** {warning_status}\n**告警等级:** {warning_level}" ,
                            "text_align": "left",
                            "text_size": "normal"
                            },
                            {"tag": "hr"},
                            {
                            "tag": "markdown",
                            "content": f"**告警主题:** {summary}\n**告警详情**: {description}",
                            "text_align": "left",
                            "text_size": "normal"
                            },
                            {"tag": "hr"},
                            {
                            "tag": "markdown",
                            "content": f"**故障时间:** {warning_start_time}\n**恢复时间:** {warning_end_time}",
                            "text_align": "left",
                            "text_size": "normal"
                            }
                        ]
                    },
                    "i18n_header": {
                        "zh_cn": {
                            "title": {
                                "tag": "plain_text",
                                "content": title
                            },
                            "subtitle": {
                                "tag": "plain_text",
                                "content": now_time_struct
                            },
                            "template": 'red' if warning_isfiring == 'firing' else 'green'
                        }
                    }
                }
            }
        try:
            session = requests.Session()
            session.mount('http://', HTTPAdapter(max_retries=3))
            session.mount('https://', HTTPAdapter(max_retries=3))
            send_data = json.dumps(send_data)
           # session.post(url, data=send_data, headers=headers, timeout=5, verify=False)
            session.post(url, data=send_data, headers=headers, timeout=5)
        except requests.exceptions.RequestException as e:
            print(e)
    session.close

  
    return {"ok"}

def send(token:str,data):
    url=settings.feishu_url_prefix+"/"+token
    headers = {'Content-Type': 'application/json; charset=utf-8'}
    alerts = data['alerts']
    for output in alerts:
        try:
            summary=output['annotations']['summary'] 
        except KeyError: 
            summary='null'  
        try:
            description=output['annotations']['description'] 
        except KeyError: 
            description='null'    
        title = f"平台监控告警通知: {output['labels']['alertname']}"
        warning_name = output['labels']['alertname']
        warning_status = output['status']  
        warning_isfiring = output['status']
        warning_level = output['labels']['severity']
        warning_instance = output['labels']['instance'] 
        warning_start_time = arrow.get(output['startsAt']).to('Asia/Shanghai').format('YYYY-MM-DD HH:mm:ss')
        warning_end_time = arrow.get(output['endsAt']).to('Asia/Shanghai').format('YYYY-MM-DD HH:mm:ss')
        now_time = str(datetime.datetime.now().replace(microsecond=0))
        now_time_struct = str(datetime.datetime.strptime(now_time, "%Y-%m-%d %H:%M:%S"))

        if settings.feishu_alert_type == "post":
            send_data={
                "msg_type": "post",
                "content":{
                    "post":{
                        "zh_cn":{
                            "title": title,
                            "content":[
                                [
                                    {"tag": "text", "text": f"告警实例: {warning_instance} \n"},
                                    {"tag": "text", "text": f"当前时间: {now_time_struct} \n"},
                                    {"tag": "text", "text": f"告警等级: {warning_level} \n"},                           
                                    {"tag": "text", "text": f"当前状态: {warning_status} \n"},
                                    {"tag": "text", "text": f"故障时间: {warning_start_time} \n"},
                                    {"tag": "text", "text": f"恢复时间: {warning_end_time} \n"},  
                                    {"tag": "text", "text": f"告警主题: {summary} \n"},
                                    {"tag": "text", "text": f"告警详情: {description} \n"},
                                ]
                            ]
                
                        }
                    }
                }
            }
        elif settings.feishu_alert_type == "interactive":
            title = f"%s告警通知" %warning_level
            send_data = {
                "msg_type": "interactive",
                "card": {
                    "config": {"update_multi": True },
                    "i18n_elements": {
                        "zh_cn": [
                            {"tag": "hr"},
                            {
                            "tag": "markdown",
                            "content": f"**告警名称:**{warning_name}\n**故障节点: **{warning_instance}\n**告警状态:** {warning_status}\n**告警等级:** {warning_level}" ,
                            "text_align": "left",
                            "text_size": "normal"
                            },
                            {"tag": "hr"},
                            {
                            "tag": "markdown",
                            "content": f"**告警主题:** {summary}\n**告警详情**: {description}",
                            "text_align": "left",
                            "text_size": "normal"
                            },
                            {"tag": "hr"},
                            {
                            "tag": "markdown",
                            "content": f"**故障时间:** {warning_start_time}\n**恢复时间:** {warning_end_time}",
                            "text_align": "left",
                            "text_size": "normal"
                            }
                        ]
                    },
                    "i18n_header": {
                        "zh_cn": {
                            "title": {
                                "tag": "plain_text",
                                "content": title
                            },
                            "subtitle": {
                                "tag": "plain_text",
                                "content": now_time_struct
                            },
                            "template": 'red' if warning_isfiring == 'firing' else 'green'
                        }
                    }
                }
            }
        try:
            session = requests.Session()
            session.mount('http://', HTTPAdapter(max_retries=3))
            session.mount('https://', HTTPAdapter(max_retries=3))
            send_data = json.dumps(send_data)
           # session.post(url, data=send_data, headers=headers, timeout=5, verify=False)
            session.post(url, data=send_data, headers=headers, timeout=5)
        except requests.exceptions.RequestException as e:
            print(e)
    session.close

  
    return {"ok"}
